package com.nes.rabbitmq.local;

import com.rabbitmq.client.*;
import org.springframework.util.SerializationUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 
 * 功能概要：读取队列的程序端，实现了Runnable接口
 * 
 * @author linbingwen
 * @since  2016年1月11日
 */
public class QueueConsumer extends EndPoint implements Runnable, Consumer {
     
    public QueueConsumer(String queueName) throws IOException, TimeoutException {
        super(queueName);
    }
     
    public void run() {
        try {
            //start consuming messages. Auto acknowledge messages.
            //消费消息，并自动确认消息
            channel.basicConsume(queueName, true,this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * Called when consumer is registered.
     */
    public void handleConsumeOk(String consumerTag) {
        System.out.println("Consumer "+consumerTag +" registered");    
    }
 
    /**
     * 处理消息
     */
    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        Map map = (HashMap) SerializationUtils.deserialize(body);
        System.out.println("Message Number "+ map.get("message number") + " received.");
    }

    public void handleCancel(String consumerTag) {}
    public void handleCancelOk(String consumerTag) {}
    public void handleRecoverOk(String consumerTag) {}
    public void handleShutdownSignal(String consumerTag, ShutdownSignalException arg1) {}
}